package com.leetcode;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @program: study
 * @description:
 * @author: kukuxiahuni
 * @create: 2019-01-29 13:18
 **/
public class Test {

    public static void main(String[] args) throws InterruptedException {

        DelayQueue<DelayTask> delayQueue = new DelayQueue<>();

        DelayTask task = new DelayTask(1, (short) (1), 10000, System.currentTimeMillis());
        delayQueue.offer(task, 10000, TimeUnit.MILLISECONDS);


        DelayTask o =
                delayQueue.take();


        System.out.println(o.getCount());

    }

    private final static class DelayTask implements Delayed {

        /**
         * 消息id
         */
        private long msgId;
        /**
         * 重试次数
         */
        private short count;

        /**
         * 过期时间(单位毫秒)
         */
        private long exprieTime;

        /**
         * 写入时间(毫秒)
         */
        private long currentTime;


        @Override
        public int compareTo(Delayed o) {
            //小的放在前面
            if (this.getDelay(TimeUnit.MICROSECONDS) > o.getDelay(TimeUnit.MICROSECONDS)) {
                return 1;
            }
            if (this.getDelay(TimeUnit.MICROSECONDS) < o.getDelay(TimeUnit.MICROSECONDS)) {
                return -1;
            }
            return 0;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return this.exprieTime - (System.currentTimeMillis() - this.currentTime);
        }

        public long getMsgId() {
            return msgId;
        }

        public void setMsgId(long msgId) {
            this.msgId = msgId;
        }

        public short getCount() {
            return count;
        }

        public void setCount(short count) {
            this.count = count;
        }

        public DelayTask(long msgId, short count, long exprieTime, long currentTime) {
            this.msgId = msgId;
            this.count = count;
            this.exprieTime = exprieTime;
            this.currentTime = currentTime;
        }

    }
}
